package com.wuda.servlet;

import com.wuda.bean.Book;
import com.wuda.dao.BookDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/allBook")
public class Books extends HttpServlet {
	private final BookDao bookDao = new BookDao();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json; charset=utf8");

		// 接收参数
		String limitStr = req.getParameter("limit");
		String pageStr = req.getParameter("page");
		String title = req.getParameter("title");
		int limit = (limitStr != null) ? Integer.parseInt(limitStr) : 10;
		int page = (pageStr != null) ? Integer.parseInt(pageStr) : 1;
		int offset = (page - 1) * limit;

		// 准备返回参数
		int code = 500;
		String msg = "无数据";
		int count = 0;
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonResult = new JSONObject();

		// 进行查询
		try {
			System.out.println("进行图书列表查询,title: " + title);
			List<Book> books = bookDao.searchBooks(title, limit, offset);
			count = bookDao.getBookCount(title);

			if (!books.isEmpty()) {
				code = 200;
				msg = "查询成功";
				for (Book book : books) {
					JSONObject jsonData = new JSONObject();
					jsonData.put("book_id", book.getBookId());
					jsonData.put("title", book.getTitle());
					jsonData.put("author", book.getAuthor());
					jsonData.put("isbn", book.getIsbn());
					jsonData.put("publisher", book.getPublisher());
					jsonData.put("publish_date", book.getPublishDate().toString());
					jsonData.put("stock_quantity", book.getStockQuantity());
					jsonData.put("type", book.getType());
					jsonData.put("introduce", book.getIntroduce());
					jsonArray.add(jsonData);
				}
			} else {
				code = 200;
				msg = "无数据";
			}
		} catch (Exception e) {
			msg = "数据库操作错误";
			e.printStackTrace();
		}

		// 返回数据
		jsonResult.put("code", code);
		jsonResult.put("count", count);
		jsonResult.put("msg", msg);
		jsonResult.put("data", jsonArray);

		try (PrintWriter out = resp.getWriter()) {
			out.print(jsonResult);
			out.flush();
		}
	}
}

